﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using GeneralUtilities.Utilities.Unity;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection;
using NoteTableUI.Models;
using UserDomain.DomainLayer;
using UserDomain.DomainLayer.Entities;
using UserDomain.ServiceLayer;

namespace NoteTableUI.Controllers
{
    public class AccountController : BaseController
    {

        private IUserService UserService { get; set; }

        public AccountController(IUserService userService)
        {
            UserService = userService;

        }
        public AccountController()
        {
            UserService = PolicyInjection.Wrap<IUserService>(Container.Resolve<UserService>());

        }


        public ActionResult LogOn()
        {
            return View();
        }

        public ActionResult LogOnNew()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOnNew(LogOnModel model, string returnUrl)
        {
            if (!ModelState.IsValid) return View(model);
            var user = new User {UserName = model.UserName, Password = model.Password};
            user = UserService.ValidateUser(user);
            if (user.UserId > 0)
            {
                Session.Add("UserId", user.UserId);
                FormsAuthentication.SetAuthCookie(user.UserName, model.RememberMe);
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                ModelState.AddModelError("", Resources.Resources.AccountController_LogOnNew_The_user_name_or_password_provided_is_incorrect_);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult RegisterNew()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (!ModelState.IsValid) return View(model);
            var user = new User {UserName = model.UserName, Password = model.Password};
            user = UserService.ValidateUser(user);
            if (user.UserId > 0)
            {
                Session.Add("UserId", user.UserId);
                FormsAuthentication.SetAuthCookie(user.UserName, model.RememberMe);
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                ModelState.AddModelError("", Resources.Resources.AccountController_LogOnNew_The_user_name_or_password_provided_is_incorrect_);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();

            return RedirectToAction("Index", "Home");
        }

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (!ModelState.IsValid) return View(model);
            var user = new User {UserName = model.UserName, Password = model.Password, Email = model.Email};
            user = UserService.RegisterUser(user);

            if (user.Status == UserStatus.Success)
            {
                Session.Add("UserId", user.UserId);
                FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", ErrorCodeToString(user.Status));
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (!ModelState.IsValid) return View(model);
            var changePasswordSucceeded = false;
            try
            {
                var currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                if (currentUser != null)
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
            }
            catch (Exception)
            {
                changePasswordSucceeded = false;
            }

            if (changePasswordSucceeded)
            {
                return RedirectToAction("ChangePasswordSuccess");
            }
            else
            {
                ModelState.AddModelError("", Resources.Resources.AccountController_ChangePassword_The_current_password_is_incorrect_or_the_new_password_is_invalid_);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        #region Status Codes
        private static string ErrorCodeToString(UserStatus userStatus)
        {
            switch (userStatus)
            {
                case UserStatus.UserNameRegistered:
                    return @Resources.Resources.ErrUserNameRegistered;

                case UserStatus.EmailRegistered:
                    return @Resources.Resources.ErrEmailRegistered;

                default:
                    return @Resources.Resources.ErrDefault;
            }
        }
        #endregion
    }
}
